// =======================================================================
// 
//       Filename:  process.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  03.05.2010 17:13:03
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  Dominik 'domachine' Burgdörfer (-), dominik.burgdoerfer@googlemail.com
//        Company:  -
// 
// =======================================================================

#include "process.hpp"

namespace webplodder {
    namespace process {
        using namespace std;

        Process::Process(const string& command)
            : m_command(command)
        {
            m_fileDescriptors[0] = -1;
            m_fileDescriptors[1] = -1;
        }

        pid_t Process::launch() {
            return popen2(m_command.c_str(), 
                   &m_fileDescriptors[WRITE], 
                   &m_fileDescriptors[READ]);
        }

        bool Process::operator>>(char& ch) {
            int check = read(m_fileDescriptors[READ], &ch, 1);
            if(check > 0)
                return true;
            else
                return false;
        }

        Process& Process::operator<<(char ch) {
            write(m_fileDescriptors[WRITE], &ch, 1);

            return *this;
        }

        void Process::closeReadChannel() {
            ::close(m_fileDescriptors[READ]);
        }

        void Process::closeWriteChannel() {
            ::close(m_fileDescriptors[WRITE]);
        }

        void Process::close() {
            ::close(m_fileDescriptors[READ]);
            ::close(m_fileDescriptors[WRITE]);
        }
    }
}
